//
//  StatusPictureView.swift
//  Weibo
//
//  Created by 孙明海 on 16/1/29.
//  Copyright © 2016年 孙明海. All rights reserved.
//

import UIKit
import SDWebImage

private let StatusPictureViewID = "StatusPictureViewID"

class StatusPictureView: UICollectionView {
    
    var statusViewModel: StatusViewModel? {
        didSet {
            sizeToFit()
            
            reloadData()
            
        }
    }
    
    init() {
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = StatusCellMargin
        layout.minimumLineSpacing = StatusCellMargin
        

        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        
        backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        dataSource = self
        
        delegate = self
        
        registerClass(StatusPictureCell.self, forCellWithReuseIdentifier: StatusPictureViewID)
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calcSize()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
   
}
// MARK: - collection view 的数据源
extension StatusPictureView: UICollectionViewDataSource,UICollectionViewDelegate {
    //代理方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let userInfo: [String: AnyObject] = [WBStatusSelectedPhotoIndexPathKey: indexPath,
            WBStatusSelectedPhotoURLsKey: (statusViewModel?.thumbnailUrls)!]
        NSNotificationCenter.defaultCenter().postNotificationName(WBStatusSelectedPhotoNotification, object: self, userInfo: userInfo)
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return statusViewModel?.thumbnailUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StatusPictureViewID, forIndexPath: indexPath) as! StatusPictureCell
        let url = statusViewModel?.thumbnailUrls![indexPath.item]
        
        cell.imageURL = url
        
        
        return cell
    }
}
// MARK: - 照片查看器展现协议
extension StatusPictureView: PhotoBrowerPresentDelegate {
    func imageViewForPresent(indexPath: NSIndexPath) -> UIImageView {
        let imageView = UIImageView()
        imageView.contentMode = .ScaleAspectFill
        imageView.clipsToBounds = true
        if let url = statusViewModel?.thumbnailUrls?[indexPath.item] {
            imageView.sd_setImageWithURL(url)
        }
        return imageView
    }
    func photoBrowerPresentFromRect(indexPath: NSIndexPath) -> CGRect {
        let cell = cellForItemAtIndexPath(indexPath)!
        let rect = self.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        return rect
    }
    func photoBrowerPresentToRect(indexPath: NSIndexPath) -> CGRect {
        guard let key = statusViewModel?.thumbnailUrls?[indexPath.item].absoluteString else {
            return CGRectZero
        }
        guard let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key) else {
            return CGRectZero
        }
        let width = UIScreen.mainScreen().bounds.width
        let height = image.size.height * width / image.size.width
        var y: CGFloat = 0
        let screenHeight = UIScreen.mainScreen().bounds.height
        if height < screenHeight {
            y = (screenHeight - height) * 0.5
        }
        return CGRectMake(0, y, width, height)
    }
}

// MARK: - 计算行高
extension StatusPictureView {
    func calcSize() -> CGSize {
        let rowCount: CGFloat = 3
        let maxWidth = UIScreen.mainScreen().bounds.width - 2 * StatusCellMargin
        let itemMaxWidth = (maxWidth - 2 * StatusCellMargin) / rowCount
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSizeMake(itemMaxWidth, itemMaxWidth)
        
        let count = statusViewModel?.thumbnailUrls?.count ?? 0
        
        if count == 0 {
            return CGSizeZero
        }
        
        if count == 1 {
            var size = CGSizeMake(150, 120)
            
            if let key = statusViewModel?.thumbnailUrls?.first?.absoluteString, let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key) {
                    
                    size = image.size
            }
            
            size.width = size.width < 40 ? 40 : size.width
            if size.width > 300 {
                let w: CGFloat = 300
                let h: CGFloat = size.height * w / size.width
                size = CGSize(width: w, height: h)
            }
            
            
            layout.itemSize = size
            
            return size
        }
        
        if count == 4 {
            let width = itemMaxWidth * 2 + StatusCellMargin
            return CGSizeMake(width, width)
        }
        
        let row = Int(CGFloat(count - 1) / rowCount + 1)
        let height = CGFloat(row) * itemMaxWidth + CGFloat(row - 1) * StatusCellMargin
        let width = maxWidth
        
        return CGSizeMake(width, height)
    }
}

class StatusPictureCell: UICollectionViewCell {
    
    
    var imageURL: NSURL? {
        didSet {
            pictureView.sd_setImageWithURL(imageURL,
                placeholderImage: nil,
                options: [SDWebImageOptions.RetryFailed,
                    SDWebImageOptions.RefreshCached])
            
        
            gifView.hidden = !(imageURL?.absoluteString.hasSuffix(".gif") ?? false)

            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(pictureView)
        pictureView.addSubview(gifView)
        
        pictureView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        
        gifView.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(pictureView)
            make.bottom.equalTo(pictureView)
        }
        
    }
    //MARK: - 懒加载控件
    private lazy var pictureView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .ScaleAspectFill
        imageView.clipsToBounds = true
        return imageView
    }()
    
    private lazy var gifView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
}
